package com.th.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.th.common.domain.UsWalletInfo;
import com.th.common.domain.UsWalletTransaction;
import com.th.common.enums.PaymentMethodType;
import com.th.common.utils.DateUtils;
import com.th.mapper.UsWalletTransactionMapper;
import com.th.service.UsUserService;
import com.th.service.UsWalletInfoService;
import com.th.service.UsWalletTransactionService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;


/**
 * @author 第五组
 * @Description TODO
 * @createTime 2023-06-24 17:01
 */
@Service
public class UsWalletTransactionServiceImpl extends ServiceImpl<UsWalletTransactionMapper, UsWalletTransaction> implements UsWalletTransactionService {
    @Resource
    private UsUserService userService;
    @Resource
    private UsWalletInfoService usWalletInfoService;

    @Resource
    private UsWalletTransactionService usWalletTransactionService;

    /***
     * 提现
     * @param paymentMethod
     * @param amount
     * @return
     */
    @Override
    public String Withdraw(Integer paymentMethod, Integer amount) {
        //先查用户钱包余额
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        if (usWalletInfo.getBalance() < amount) {
            return "余额不足！";
        } else {
            //业务流程 先扣余额，再添加记录
            usWalletInfo.setBalance(usWalletInfo.getBalance() - amount);
            usWalletInfo.setTotalExpenditure(usWalletInfo.getTotalExpenditure()+amount);
            usWalletInfoService.updateById(usWalletInfo);
            //封装账单项目
            UsWalletTransaction usWalletTransaction = new UsWalletTransaction();
            usWalletTransaction.setWalletId(usWalletInfo.getId());
            usWalletTransaction.setType(0);
            usWalletTransaction.setStatus(0);
            usWalletTransaction.setPaymentMethod(paymentMethod);
            usWalletTransaction.setPaymentInfo("提现到" + PaymentMethodType.of(paymentMethod).getName());
            usWalletTransaction.setAmountMoney(amount);
            usWalletTransaction.setCreateTime(DateUtils.getNowDate());
            //添加记录
            usWalletTransactionService.save(usWalletTransaction);
        }
        return "successful";
    }

    /***
     * 充值
     * @param paymentMethod
     * @param amount
     * @return
     */
    @Override
    public String Recharge(Integer paymentMethod, Integer amount) {
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        usWalletInfo.setBalance(usWalletInfo.getBalance() + amount);
        usWalletInfo.setTotalIncome(usWalletInfo.getTotalIncome()+amount);
        //更新账户余额
        usWalletInfoService.updateById(usWalletInfo);
        //封装账单项目
        UsWalletTransaction usWalletTransaction = new UsWalletTransaction();
        usWalletTransaction.setWalletId(usWalletInfo.getId());
        usWalletTransaction.setPaymentMethod(paymentMethod);
        usWalletTransaction.setPaymentInfo("通过" + PaymentMethodType.of(paymentMethod).getName() + "充值到钱包");
        usWalletTransaction.setType(1);
        usWalletTransaction.setStatus(1);
        usWalletTransaction.setAmountMoney(amount);
        usWalletTransaction.setCreateTime(DateUtils.getNowDate());
        usWalletTransactionService.save(usWalletTransaction);
        return "successful!";
    }


    /***
     * 分页查询
     * @return
     */
    @Override
    public LambdaQueryWrapper<UsWalletTransaction> getUsWalletTransaction() {
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        LambdaQueryWrapper<UsWalletTransaction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(usWalletInfo.getId().toString()), UsWalletTransaction::getWalletId, usWalletInfo.getId())
                .orderByDesc(UsWalletTransaction::getCreateTime);
        return lambdaQueryWrapper;
    }


    /**
     * 给定一个日期区间查询账单，以分页形式展示
     * 这里提供一个（LambdaQueryWrapper）查询条件
     * @param startTime
     * @param endTime
     * @return （LambdaQueryWrapper）查询条件
     */
    @Override
    public LambdaQueryWrapper<UsWalletTransaction> getUsWalletTransactionCompareByTime(Date startTime, Date endTime, Integer type){
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        LambdaQueryWrapper<UsWalletTransaction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(UsWalletTransaction::getCreateTime,startTime)
                .le(UsWalletTransaction::getCreateTime,endTime)
                .eq(UsWalletTransaction::getWalletId,usWalletInfo.getId())
                .eq(UsWalletTransaction::getType,type);
        return lambdaQueryWrapper;
    }

    /***
     * 获取当月支出
     * @param month
     * @param year
     * @return
     */
    @Override
    public String getCurrentMonthExpenditure(Integer month, Integer year) {
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        QueryWrapper<UsWalletTransaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("YEAR(create_time)={0} AND MONTH(create_time)={1}", year, month)
                .select("sum(amount_money) as totalPrice")
                .eq("wallet_id", usWalletInfo.getId()).eq("type", 0);
        Object obj = this.baseMapper.selectObjs(queryWrapper).get(0);
        if (obj == null) {
            //如果为空，则月支出为0，直接返回
            return "0";
        } else {
            String currentMonthExpenditure = obj.toString();
            return currentMonthExpenditure;
        }
    }

    /***
     * 获取当月收入
     * @param month
     * @param year
     * @return
     */
    @Override
    public String getCurrentMonthIncome(Integer month, Integer year) {
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        QueryWrapper<UsWalletTransaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("YEAR(create_time)={0} AND MONTH(create_time)={1}", year, month)
                .select("sum(amount_money) as totalPrice")
                .eq("wallet_id", usWalletInfo.getId()).eq("type", 1);
        Object obj = this.baseMapper.selectObjs(queryWrapper).get(0);
        if (obj == null) {
            //如果为空，则月收入为0，直接返回
            return "0";
        } else {
            String currentMonthIncome = obj.toString();
            return currentMonthIncome;
        }
    }

    /***
     * 获取支出与收入
     * @param type 类型
     * @return
     */
    @Override
    public LambdaQueryWrapper<UsWalletTransaction> getIncomeAndExpenditure(Integer type){
        UsWalletInfo usWalletInfo = usWalletInfoService.getWalletInfo();
        LambdaQueryWrapper<UsWalletTransaction> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(usWalletInfo.getId().toString()), UsWalletTransaction::getWalletId, usWalletInfo.getId())
                .eq(UsWalletTransaction::getType,type)
                .orderByDesc(UsWalletTransaction::getCreateTime);
        return lambdaQueryWrapper;
    }
}
